package cz.uvn.orthopedy.client.ui.editor;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import cz.uvn.orthopedy.client.ApplicationController;
import cz.uvn.orthopedy.client.entity.JournalEntry;
import cz.uvn.orthopedy.client.entity.Patient;

public class JournalEntryEditor extends DialogBox implements ClickHandler {
	private ApplicationController controller;
	
	private OperationEditor operationEditor;
	private PatientEditor patientEditor;
	
	private Button okButton;
	private Button cancelButton;
	
	public JournalEntryEditor(final JournalEntry entry, final ApplicationController controller) {
		this.controller = controller;
		
		setAnimationEnabled(true);
		setText(entry == null ? "Vytvořit Nový Operační Záznam" : "Korekce Operačního Záznamu");

		operationEditor = new OperationEditor(entry, controller.getHallsCache(), controller.getDoctorsCache());
		Patient patient = null;
		if (entry != null) {
			patient = controller.getPatientByID(entry.getPatientID());
		}
		patientEditor = new PatientEditor(patient, controller.getInsurancesCache());

		DecoratedTabPanel tabbedPanel = new DecoratedTabPanel();
		tabbedPanel.add(operationEditor, "Operace");
		tabbedPanel.add(patientEditor, "Pacient");
		tabbedPanel.selectTab(0);

		AbsolutePanel buttonsPanel = new AbsolutePanel();
		buttonsPanel.setSize("100%", "45px");
		
		okButton = new Button("OK");
		okButton.addClickHandler(this);
		buttonsPanel.add(okButton, 324, 10);

		cancelButton = new Button("Zrušit");
		cancelButton.addClickHandler(this);
		buttonsPanel.add(cancelButton, 368, 10);
		
		VerticalPanel vPanel = new VerticalPanel();
		vPanel.add(tabbedPanel);
		vPanel.add(buttonsPanel);
		
		setWidget(vPanel);
	}

	@Override
	public void onClick(ClickEvent event) {
		if (event.getSource() == cancelButton) {
			hide();
		} else if (event.getSource() == okButton) {
			if (operationEditor.isValid() && patientEditor.isValid()) {
				JournalEntry entry = operationEditor.getEntry();
				Patient patient = patientEditor.getPatinet();
				
				controller.saveEntry(entry, patient);
				hide();
			}
		}
	}
}
